import React, { useEffect, useState } from 'react';
import type { Tab } from '../types';
import { getAllTabs, createTab, deleteTab, updateTab, getTab } from '../api';
import Tabs from '../components/Tabs';
import CardsViews from '../components/CardsViews';


const Home: React.FC = () => {
    const [tab, setTab] = useState<Tab | null>(null)
    const [tabs, setTabs] = useState<Tab[]>([]);

    const handleTabClick = async (data: Tab) => {
        const res = await getTab(data.id);
        if (res.data) {
            setTab(res.data);
        }
    };

    const getTabs = async (delId?: string) => {
        const res = await getAllTabs();
        if (res.data) {
            setTabs(res.data);
            if (tab?.id === delId || !tab?.id) {
                setTab(res.data[0] || null)
            }
        }
    };

    const handleAddTab = async () => {
        const newTabName = prompt('请输入标签名称:');
        if (newTabName) {
            await createTab({ name: newTabName, scale: 1, offsetX: 0, offsetY: 0 });
            getTabs();
        }
    };

    const handleDeleteTab = async (tabId: string) => {
        await deleteTab(tabId);
        getTabs(tabId);
    };

    const handleUpdateTab = async (tabName: string) => {
        const newTabName = prompt('请输入标签名称:', tabName);
        if (newTabName && tab?.id) {
            await updateTab(tab?.id, { name: newTabName });
            getTabs();
        }
    };

    // 初始化所有标签的视图状态
    useEffect(() => {
        getTabs();
    }, []);

    return (
        <div className="home-container">
            <Tabs
                tabs={tabs}
                activeTabId={tab?.id}
                onTabClick={handleTabClick}
                onAddTab={handleAddTab}
                onDeleteTab={handleDeleteTab}
                onTabUpdate={handleUpdateTab}
            />
            {tab?.id && (
                <CardsViews tab={tab} key={tab.id} />
            )}
        </div>
    );
};

export default Home;